package com.zoffy.catdiarybackend.websocket;
import com.zoffy.catdiarybackend.model.vo.UserVo;
import com.zoffy.catdiarybackend.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.*;

@Component
public class SocketAuthInterceptor implements HandshakeInterceptor {
    @Autowired
    private UserService userService;
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        HttpHeaders headers = request.getHeaders();
        String cookieString=headers.getFirst("Cookie");
        Map<String,String> cookies=new HashMap<>();
        if (cookieString==null){
            return false;
        }
        for(String s: cookieString.split(";")){
            String[] value = s.split("=");
            cookies.put(value[0],value[1]);

        }

        String sessionId = cookies.get("JSESSIONID");
        UserVo userVo = userService.getUserVo(sessionId);
        String articleId = headers.getFirst("articleId");
        attributes.put("articleId",articleId);
        //todo 在这里进行是否对当前文章具有协作权限
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
